import { useEffect, useCallback, useRef } from 'react'
import { usePerformanceMonitor } from '@/utils/performance'
import { useApiCache, apiCache } from '@/utils/apiCache'
import { usePreloader, dataPreloader, DataPreloadStrategy, smartPreloader } from '@/utils/preloader'
import { api as optimizedApi } from '@/lib/api'

// 性能优化配置接口
export interface PerformanceConfig {
    enablePreloading?: boolean
    enableCaching?: boolean
    enableMonitoring?: boolean
    preloadStrategy?: DataPreloadStrategy
    cacheTimeout?: number
    maxConcurrentRequests?: number
}

// 默认配置
const DEFAULT_CONFIG: PerformanceConfig = {
    enablePreloading: true,
    enableCaching: true,
    enableMonitoring: true,
    preloadStrategy: DataPreloadStrategy.ON_IDLE,
    cacheTimeout: 5 * 60 * 1000, // 5分钟
    maxConcurrentRequests: 3
}

// 性能优化 Hook
export function usePerformanceOptimization(config: PerformanceConfig = {}) {
    const finalConfig = { ...DEFAULT_CONFIG, ...config }
    const { startTiming, recordMetric } = usePerformanceMonitor()
    const { cacheApiCall, prefetch, invalidate } = useApiCache()
    const { preloadResource } = usePreloader()
    // Get intersection observer methods from dataPreloader
    const observeElement = (element: Element, preloadKey: string) => dataPreloader.observeElement(element, preloadKey)
    const unobserveElement = (element: Element) => dataPreloader.unobserveElement(element)
    const observedElements = useRef(new Set<Element>())

    // 预加载数据集
    const preloadDatasets = useCallback(async () => {
        if (!finalConfig.enablePreloading) return

        try {
            dataPreloader.addPreloadTask({
                key: 'datasets_critical',
                priority: 10,
                strategy: finalConfig.preloadStrategy!,
                loader: () => optimizedApi.getDatasets(),
                estimatedSize: 5120
            })
        } catch (error) {
            console.warn('Failed to preload datasets:', error)
        }
    }, [finalConfig.enablePreloading, finalConfig.preloadStrategy])

    // 预加载特定数据集
    const preloadDataset = useCallback((datasetId: string, priority = 5) => {
        if (!finalConfig.enablePreloading) return

        dataPreloader.addPreloadTask({
            key: `dataset_${datasetId}`,
            priority,
            strategy: DataPreloadStrategy.ON_HOVER,
            loader: () => optimizedApi.getDataset(datasetId),
            dependencies: ['datasets_critical'],
            estimatedSize: 1024
        })
    }, [finalConfig.enablePreloading])

    // 预加载图像数据
    const preloadImageData = useCallback((imageId: string, priority = 3) => {
        if (!finalConfig.enablePreloading) return

        dataPreloader.addPreloadTask({
            key: `image_${imageId}`,
            priority,
            strategy: DataPreloadStrategy.ON_VIEWPORT,
            loader: () => optimizedApi.getImageData(imageId),
            estimatedSize: 1024 * 1024, // 1MB
            timeout: 30000
        })
    }, [finalConfig.enablePreloading])

    // 预加载任务列表
    const preloadTasks = useCallback((datasetId: string, priority = 4) => {
        if (!finalConfig.enablePreloading) return

        dataPreloader.addPreloadTask({
            key: `tasks_${datasetId}`,
            priority,
            strategy: DataPreloadStrategy.ON_IDLE,
            loader: () => optimizedApi.getTasks(datasetId),
            dependencies: [`dataset_${datasetId}`],
            estimatedSize: 2048
        })
    }, [finalConfig.enablePreloading])

    // 智能预加载 - 基于用户行为
    const smartPreload = useCallback((currentPath: string, userInteractions: string[]) => {
        if (!finalConfig.enablePreloading) return

        // 基于当前路径预测下一步操作
        if (currentPath === '/') {
            // 在首页，预加载热门数据集
            preloadDatasets()
        } else if (currentPath.startsWith('/dataset/')) {
            const datasetId = currentPath.split('/')[2]
            if (datasetId) {
                preloadTasks(datasetId)
                // 预加载该数据集的前几张图像
                optimizedApi.getDataset(datasetId).then(dataset => {
                    if (dataset.images && dataset.images.length > 0) {
                        dataset.images.slice(0, 3).forEach(image => {
                            preloadImageData(image.id, 2)
                        })
                    }
                }).catch(() => { })
            }
        }

        // 基于用户交互历史预测
        userInteractions.forEach((interaction, index) => {
            if (interaction.startsWith('dataset_')) {
                const datasetId = interaction.replace('dataset_', '')
                preloadDataset(datasetId, 10 - index)
            }
        })
    }, [finalConfig.enablePreloading, preloadDatasets, preloadTasks, preloadImageData, preloadDataset])

    // 观察元素进入视口
    const observeForPreload = useCallback((element: Element, preloadKey: string) => {
        if (!finalConfig.enablePreloading) return

        observeElement(element, preloadKey)
        observedElements.current.add(element)
    }, [finalConfig.enablePreloading, observeElement])

    // 停止观察元素
    const stopObserving = useCallback((element: Element) => {
        unobserveElement(element)
        observedElements.current.delete(element)
    }, [unobserveElement])

    // 缓存API调用
    const cachedApiCall = useCallback(async <T>(
        key: string,
        apiCall: () => Promise<T>,
        cacheType: 'datasets' | 'images' | 'tasks' | 'metadata' = 'datasets'
    ): Promise<T> => {
        if (!finalConfig.enableCaching) {
            return apiCall()
        }

        return cacheApiCall(cacheType, key, apiCall, {
            ttl: finalConfig.cacheTimeout
        })
    }, [finalConfig.enableCaching, finalConfig.cacheTimeout, cacheApiCall])

    // 测量组件渲染性能
    const measureRender = useCallback((componentName: string) => {
        if (!finalConfig.enableMonitoring) return () => { }

        return startTiming(`render_${componentName}`)
    }, [finalConfig.enableMonitoring, startTiming])

    // 测量API调用性能
    const measureApiCall = useCallback((apiName: string) => {
        if (!finalConfig.enableMonitoring) return () => { }

        return startTiming(`api_${apiName}`)
    }, [finalConfig.enableMonitoring, startTiming])

    // 记录用户交互性能
    const recordInteraction = useCallback((interactionType: string, duration: number) => {
        if (!finalConfig.enableMonitoring) return

        recordMetric(`interaction_${interactionType}`, duration)
    }, [finalConfig.enableMonitoring, recordMetric])

    // 优化图像加载
    const optimizeImageLoading = useCallback((imageUrls: string[]) => {
        if (!finalConfig.enablePreloading) return

        // 使用 Intersection Observer 延迟加载图像
        imageUrls.forEach((url, index) => {
            dataPreloader.addPreloadTask({
                key: `image_url_${url}`,
                priority: 5 - index,
                strategy: DataPreloadStrategy.ON_VIEWPORT,
                loader: async () => {
                    return new Promise((resolve, reject) => {
                        const img = new Image()
                        img.onload = () => resolve(img)
                        img.onerror = reject
                        img.src = url
                    })
                },
                estimatedSize: 500 * 1024 // 500KB 估算
            })
        })
    }, [finalConfig.enablePreloading])

    // 批量预取数据
    const batchPreload = useCallback(async (requests: Array<{
        key: string
        loader: () => Promise<any>
        priority?: number
        strategy?: DataPreloadStrategy
    }>) => {
        if (!finalConfig.enablePreloading) return

        const tasks = requests.map(req => ({
            key: req.key,
            priority: req.priority || 5,
            strategy: req.strategy || DataPreloadStrategy.ON_IDLE,
            loader: req.loader,
            estimatedSize: 1024
        }))

        tasks.forEach(task => dataPreloader.addPreloadTask(task))
        await dataPreloader.executePreload(finalConfig.maxConcurrentRequests)
    }, [finalConfig.enablePreloading, finalConfig.maxConcurrentRequests])

    // 清理缓存
    const clearCache = useCallback((type?: 'datasets' | 'images' | 'tasks' | 'metadata') => {
        invalidate(type as any)
    }, [invalidate])

    // 获取性能统计
    const getPerformanceStats = useCallback(() => {
        return {
            cache: apiCache.getStats(),
            preloader: dataPreloader.getStats()
        }
    }, [])

    // 清理函数
    useEffect(() => {
        return () => {
            // 清理所有观察的元素
            observedElements.current.forEach(element => {
                unobserveElement(element)
            })
            observedElements.current.clear()
        }
    }, [unobserveElement])

    return {
        // 预加载方法
        preloadDatasets,
        preloadDataset,
        preloadImageData,
        preloadTasks,
        smartPreload,
        batchPreload,

        // 视口观察
        observeForPreload,
        stopObserving,

        // 缓存方法
        cachedApiCall,
        clearCache,

        // 性能监控
        measureRender,
        measureApiCall,
        recordInteraction,

        // 图像优化
        optimizeImageLoading,

        // 统计信息
        getPerformanceStats,

        // 配置
        config: finalConfig
    }
}

// 专门用于数据集页面的性能优化 Hook
export function useDatasetPerformanceOptimization(datasetId?: string) {
    const perf = usePerformanceOptimization({
        preloadStrategy: DataPreloadStrategy.ON_HOVER,
        cacheTimeout: 10 * 60 * 1000 // 10分钟缓存
    })

    useEffect(() => {
        if (datasetId) {
            // 预加载当前数据集的相关数据
            perf.preloadDataset(datasetId, 10)
            perf.preloadTasks(datasetId, 8)

            // 智能预加载相关数据集
            perf.smartPreload(`/dataset/${datasetId}`, [`dataset_${datasetId}`])
        }
    }, [datasetId, perf])

    return perf
}

// 专门用于任务页面的性能优化 Hook
export function useTaskPerformanceOptimization(datasetId?: string, taskId?: string) {
    const perf = usePerformanceOptimization({
        preloadStrategy: DataPreloadStrategy.IMMEDIATE,
        cacheTimeout: 2 * 60 * 1000 // 2分钟缓存（任务状态变化较快）
    })

    useEffect(() => {
        if (datasetId && taskId) {
            // 预加载任务相关数据
            perf.batchPreload([
                {
                    key: `task_${taskId}`,
                    loader: () => optimizedApi.getTaskStatus(taskId),
                    priority: 10,
                    strategy: DataPreloadStrategy.IMMEDIATE
                },
                {
                    key: `task_results_${taskId}`,
                    loader: () => optimizedApi.getTaskResults(taskId),
                    priority: 8,
                    strategy: DataPreloadStrategy.ON_IDLE
                }
            ])
        }
    }, [datasetId, taskId, perf])

    return perf
}